<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理 - 商品列表</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.0/font/bootstrap-icons.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4f46e5;
            --primary-hover: #4338ca;
            --success-color: #10b981;
            --danger-color: #ef4444;
            --warning-color: #f59e0b;
        }

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding-top: 70px; /* 为固定导航栏留出空间 */
        }

        /* 导航栏样式 */
        .top-navbar {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1030;
        }

        .top-navbar .navbar-brand {
            font-size: 1.3rem;
            letter-spacing: 0.5px;
            font-weight: 700;
        }

        .top-navbar .nav-link {
            color: rgba(255,255,255,0.85) !important;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            margin: 0 0.2rem;
            transition: all 0.2s;
        }

        .top-navbar .nav-link:hover,
        .top-navbar .nav-link.active {
            background: rgba(255,255,255,0.15);
            color: white !important;
        }

        .main-container {
            padding: 2rem 0;
        }

        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
        }

        .header-section {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
            color: white;
            padding: 2rem;
            border-radius: 15px 15px 0 0;
            margin: -1.5rem -1.5rem 1.5rem -1.5rem;
        }

        .search-box {
            border-radius: 25px;
            border: 2px solid #e5e7eb;
            padding: 0.6rem 1.2rem;
            transition: all 0.3s;
        }

        .search-box:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
            border: none;
            border-radius: 25px;
            padding: 0.6rem 1.5rem;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.3);
        }

        .table {
            border-radius: 10px;
            overflow: hidden;
        }

        .table thead {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        }

        .table tbody tr {
            transition: all 0.2s;
        }

        .table tbody tr:hover {
            background-color: #f8f9fa;
            transform: scale(1.01);
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 500;
        }

        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 10px;
            border: 2px solid #f3f4f6;
        }

        .action-btn {
            padding: 0.4rem 0.8rem;
            margin: 0 0.2rem;
            border-radius: 8px;
            transition: all 0.2s;
        }

        .action-btn:hover {
            transform: scale(1.1);
        }

        .pagination {
            gap: 0.3rem;
        }

        .page-link {
            border-radius: 8px;
            border: none;
            margin: 0 0.2rem;
            color: var(--primary-color);
        }

        .page-item.active .page-link {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
        }

        .filter-section {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
        }

        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 0.5rem;
        }
    </style>
</head>

<script>
    // 自动高亮当前页面的导航项
    document.addEventListener('DOMContentLoaded', function() {
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('.top-navbar .nav-link');

        // 移除所有active类
        navLinks.forEach(link => link.classList.remove('active'));

        // 根据当前路径添加active类
        navLinks.forEach(link => {
            const href = link.getAttribute('href');
            if (currentPath === href ||
                (href !== '/dashboard' && currentPath.startsWith(href))) {
                link.classList.add('active');
            }
        });
    });
</script>

<body>
<!-- 顶部导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark top-navbar">
    <div class="container-fluid">
        <a class="navbar-brand fw-bold" href="/dashboard">
            <i class="bi bi-box-seam-fill me-2"></i>商品管理系统
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/dashboard">
                        <i class="bi bi-speedometer2"></i> Dashboard
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/product/list">
                        <i class="bi bi-box"></i> 商品管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/category/list">
                        <i class="bi bi-tags"></i> 分类管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/log/list">
                        <i class="bi bi-clock-history"></i> 操作日志
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/doc">
                        <i class="bi bi-book"></i> API文档
                    </a>
                </li>
            </ul>
            <div class="d-flex align-items-center">
                <!-- 用户信息 -->
                <div th:if="${currentUser}" class="me-3 text-white">
                    <small>欢迎,</small>
                    <strong th:text="${currentUser.realName ?: currentUser.username}"></strong>
                </div>
                
                <a href="/product/add" class="btn btn-light btn-sm me-2">
                    <i class="bi bi-plus-circle"></i> 新增商品
                </a>
                <a href="/druid" target="_blank" class="btn btn-outline-light btn-sm me-2">
                    <i class="bi bi-speedometer"></i> 监控
                </a>
                <!-- 登出按钮 -->
                <a href="/auth/logout" class="btn btn-outline-light btn-sm">
                    <i class="bi bi-box-arrow-right"></i> 登出
                </a>
            </div>
        </div>
    </div>
</nav>

<div class="container main-container">
    <div class="card">
        <div class="card-body p-4">
            <!-- 页面标题 -->
            <div class="header-section">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h2 class="mb-2"><i class="bi bi-box-seam"></i> 商品管理</h2>
                        <p class="mb-0 opacity-75">管理您的商品库存和信息</p>
                    </div>
                    <a href="/product/add" class="btn btn-light btn-lg">
                        <i class="bi bi-plus-circle"></i> 新增商品
                    </a>
                </div>
            </div>

            <!-- 筛选区域 -->
            <div class="filter-section">
                <form method="get" action="/product/list" class="row g-3">
                    <div class="col-md-4">
                        <input type="text" class="form-control search-box" name="keyword"
                               th:value="${keyword}" placeholder="搜索商品名称/编码/品牌...">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select search-box" name="categoryId">
                            <option value="">全部分类</option>
                            <option th:each="cat : ${categories}"
                                    th:value="${cat.id}"
                                    th:text="${cat.categoryName}"
                                    th:selected="${cat.id == categoryId}"></option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select search-box" name="status">
                            <option value="">全部状态</option>
                            <option value="1" th:selected="${status == 1}">在售</option>
                            <option value="0" th:selected="${status == 0}">下架</option>
                            <option value="2" th:selected="${status == 2}">缺货</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select search-box" name="sortBy">
                            <option value="created_at" th:selected="${sortBy == 'created_at'}">创建时间</option>
                            <option value="sale_price" th:selected="${sortBy == 'sale_price'}">价格</option>
                            <option value="sales_count" th:selected="${sortBy == 'sales_count'}">销量</option>
                            <option value="stock_quantity" th:selected="${sortBy == 'stock_quantity'}">库存</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-search"></i> 搜索
                        </button>
                    </div>
                </form>
            </div>

            <!-- 批量操作按钮 -->
            <div class="mb-3">
                <button class="btn btn-danger btn-sm" onclick="batchDelete()">
                    <i class="bi bi-trash"></i> 批量删除
                </button>
                <button class="btn btn-success btn-sm" onclick="batchUpdateStatus(1)">
                    <i class="bi bi-check-circle"></i> 批量上架
                </button>
                <button class="btn btn-warning btn-sm" onclick="batchUpdateStatus(0)">
                    <i class="bi bi-x-circle"></i> 批量下架
                </button>
            </div>

            <!-- 商品列表表格 -->
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll" onchange="toggleSelectAll()"></th>
                        <th>图片</th>
                        <th>商品名称</th>
                        <th>编码</th>
                        <th>分类</th>
                        <th>价格</th>
                        <th>库存</th>
                        <th>状态</th>
                        <th>销量</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr th:each="product : ${pageData.records}">
                        <td><input type="checkbox" class="product-checkbox" th:value="${product.id}"></td>
                        <td>
                            <img th:src="${product.imageUrl ?: '/images/default-product.png'}"
                                 class="product-image" alt="商品图片">
                        </td>
                        <td>
                            <strong th:text="${product.productName}"></strong>
                            <br>
                            <small class="text-muted" th:text="${product.brand}"></small>
                        </td>
                        <td><code th:text="${product.productCode}"></code></td>
                        <td><span class="badge bg-info" th:text="${product.categoryName}"></span></td>
                        <td>
                            <strong class="text-success">¥<span th:text="${#numbers.formatDecimal(product.salePrice, 1, 2)}"></span></strong>
                        </td>
                        <td>
                                    <span th:classappend="${product.lowStock} ? 'text-danger' : 'text-success'"
                                          th:text="${product.stockQuantity}"></span>
                            <span th:if="${product.lowStock}" class="badge bg-warning ms-1">
                                        <i class="bi bi-exclamation-triangle"></i>
                                    </span>
                        </td>
                        <td>
                            <span th:if="${product.status == 1}" class="badge bg-success">在售</span>
                            <span th:if="${product.status == 0}" class="badge bg-secondary">下架</span>
                            <span th:if="${product.status == 2}" class="badge bg-danger">缺货</span>
                        </td>
                        <td><span th:text="${product.salesCount}"></span></td>
                        <td>
                            <a th:href="@{/product/detail/{id}(id=${product.id})}"
                               class="btn btn-info btn-sm action-btn" title="查看详情">
                                <i class="bi bi-eye"></i>
                            </a>
                            <a th:href="@{/product/edit/{id}(id=${product.id})}"
                               class="btn btn-primary btn-sm action-btn" title="编辑">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <button class="btn btn-danger btn-sm action-btn delete-btn"
                                    th:data-id="${product.id}" title="删除">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <nav th:if="${pageData.totalPages > 1}">
                <ul class="pagination justify-content-center">
                    <li class="page-item" th:classappend="${pageData.currentPage == 1} ? 'disabled'">
                        <a class="page-link" th:href="@{/product/list(page=${pageData.currentPage - 1}, size=${pageData.pageSize}, keyword=${keyword}, categoryId=${categoryId}, status=${status})}">
                            <i class="bi bi-chevron-left"></i>
                        </a>
                    </li>
                    <li class="page-item" th:each="i : ${#numbers.sequence(1, pageData.totalPages)}"
                        th:classappend="${i == pageData.currentPage} ? 'active'">
                        <a class="page-link" th:href="@{/product/list(page=${i}, size=${pageData.pageSize}, keyword=${keyword}, categoryId=${categoryId}, status=${status})}"
                           th:text="${i}"></a>
                    </li>
                    <li class="page-item" th:classappend="${pageData.currentPage == pageData.totalPages} ? 'disabled'">
                        <a class="page-link" th:href="@{/product/list(page=${pageData.currentPage + 1}, size=${pageData.pageSize}, keyword=${keyword}, categoryId=${categoryId}, status=${status})}">
                            <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>

            <div class="text-center text-muted mt-3">
                共 <strong th:text="${pageData.total}"></strong> 条记录，
                第 <strong th:text="${pageData.currentPage}"></strong> / <strong th:text="${pageData.totalPages}"></strong> 页
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="bi bi-exclamation-triangle"></i> 确认删除</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除选中的商品吗？此操作不可撤销！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
    let deleteId = null;
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

    // 全选/取消全选
    function toggleSelectAll() {
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('.product-checkbox');
        checkboxes.forEach(cb => cb.checked = selectAll.checked);
    }

    // 使用事件委托处理删除按钮点击
    document.addEventListener('click', function(e) {
        if (e.target.closest('.delete-btn')) {
            const btn = e.target.closest('.delete-btn');
            deleteId = btn.getAttribute('data-id');
            deleteModal.show();
        }
    });

    // 确认删除
    function confirmDelete() {
        if (deleteId) {
            $.ajax({
                url: `/product/delete/${deleteId}`,
                type: 'DELETE',
                success: function(result) {
                    if (result.success) {
                        alert('删除成功！');
                        location.reload();
                    } else {
                        alert('删除失败：' + result.message);
                    }
                },
                error: function() {
                    alert('删除失败，请稍后重试！');
                }
            });
        }
    }

    function batchDelete() {
        const selectedIds = getSelectedIds();
        if (selectedIds.length === 0) {
            alert('请先选择要删除的商品！');
            return;
        }

        if (confirm(`确定要删除选中的 ${selectedIds.length} 个商品吗？`)) {
            $.ajax({
                url: '/product/batchDelete',
                type: 'DELETE',
                contentType: 'application/json',
                data: JSON.stringify(selectedIds),
                success: function(result) {
                    if (result.success) {
                        alert('批量删除成功！');
                        location.reload();
                    } else {
                        alert('批量删除失败：' + result.message);
                    }
                }
            });
        }
    }

    function batchUpdateStatus(status) {
        const selectedIds = getSelectedIds();
        if (selectedIds.length === 0) {
            alert('请先选择商品！');
            return;
        }

        $.ajax({
            url: '/product/batchUpdateStatus',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({ids: selectedIds, status: status}),
            success: function(result) {
                if (result.success) {
                    alert('批量更新成功！');
                    location.reload();
                } else {
                    alert('批量更新失败：' + result.message);
                }
            }
        });
    }

    function getSelectedIds() {
        const checkboxes = document.querySelectorAll('.product-checkbox:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }
</script>
</body>
</html>